package com.zpz.framework.zpzoauth.common.verificationcode;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author zhangpanzhi
 * @time 2019-07-09
 * @description 未经本人允许请勿随便改动，尊重劳动
 * */
@Component
public class ZpzOauthRedisVerificationCodeCache {

    @Autowired
    private RedisTemplate redisTemplate;

    public void set(String cacheName, String key, String value, long expire){
        redisTemplate.opsForValue().set(cacheName + ":" + key,value);
        redisTemplate.expire(cacheName + ":" + key,expire, TimeUnit.MILLISECONDS);
    }

    public void remove(String cacheName, String key) {
        redisTemplate.delete(cacheName + ":" + key);
    }

    public String get(String cacheName, String key){
        Object o = redisTemplate.opsForValue().get(cacheName + ":" + key);
        return o!=null?o.toString():null;
    }

    public boolean validate(String cacheName, String key, String value){
        String originValue = get(cacheName,key);
        if(StringUtils.isNotEmpty(originValue)){
            return originValue.equals(value);
        }
        return  false;
    }

    public boolean isExpire(String cacheName, String key) {
        return redisTemplate.opsForValue().get(cacheName + ":" + key) == null;
    }
}
